package brcl.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect  //切面
@Component
@Slf4j
public class LogAspect {
    //注解声明切面  execution规定拦截哪些类
    @Pointcut("execution(* brcl.controller.*.*(..))")
    public void log() {
    }

    //前置通知
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL() + "";
        String ip = request.getRemoteAddr();
        //获取类名 方法名
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        Requesting requesting = new Requesting(url, ip, classMethod, args);
        log.info("requesting:{}" + requesting);
    }

    //后置通知
    @After("log()")
    public void doAfter() {
        log.info("text:after");
    }

    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterReturn(Object result) {
        log.info("result:{}" + result);
    }

    //*请求url、*访问者ip、*调用方法classMethod、*参数args、*返回内容
    public class Requesting {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public Requesting(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
